<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>WebSocket聊天测试</title>
    <script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>
    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .section {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ccc;
        }

        .message-list {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 10px;
            margin: 10px 0;
        }

        .input-group {
            margin: 10px 0;
        }

        label {
            display: inline-block;
            width: 100px;
        }

        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
            background-color: #f5f5f5;
        }

        .message.sent {
            background-color: #e3f2fd;
            text-align: right;
            color: #2979ff;
        }

        .message.received {
            background-color: #f5f5f5;
            text-align: left;
            color: #333;
        }

        .message.system {
            background-color: #fafafa;
            text-align: center;
            color: #999;
            font-style: italic;
        }

        .message.error {
            background-color: #ffebee;
            text-align: center;
            color: #ff5252;
        }

        .status {
            margin-top: 5px;
            font-size: 12px;
            color: #666;
        }

        .status.online {
            color: #4caf50;
        }

        .status.offline {
            color: #f44336;
        }

        button {
            padding: 5px 10px;
            margin-right: 5px;
            cursor: pointer;
        }

        button:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }

        input {
            padding: 5px;
            margin-right: 5px;
        }

        .error {
            color: #f44336;
            font-size: 12px;
            margin-top: 5px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="section">
            <h2>登录</h2>
            <div class="input-group">
                <label>用户名：</label>
                <input type="text" id="username" value="user1">
            </div>
            <div class="input-group">
                <label>密码：</label>
                <input type="password" id="password" value="admin123">
            </div>
            <div class="input-group">
                <label>验证码：</label>
                <input type="text" id="captcha" style="width: 100px;">
                <img id="captchaImg" style="vertical-align: middle; cursor: pointer;" onclick="refreshCaptcha()">
            </div>
            <div class="input-group">
                <button onclick="login()">登录</button>
            </div>
            <div id="loginError" class="error"></div>
        </div>

        <div class="section">
            <h2>WebSocket 连接</h2>
            <div class="input-group">
                <label>Token：</label>
                <input type="text" id="token" style="width: 300px;" readonly>
            </div>
            <div class="input-group">
                <button onclick="connect()" id="connectBtn">连接</button>
                <button onclick="disconnect()" id="disconnectBtn" disabled>断开</button>
            </div>
            <div id="connectionStatus" class="status offline">未连接</div>
        </div>

        <div class="section">
            <h2>发送消息</h2>
            <div class="input-group">
                <label>接收用户ID：</label>
                <input type="text" id="toUserId">
            </div>
            <div class="input-group">
                <label>消息内容：</label>
                <input type="text" id="messageContent">
            </div>
            <div class="input-group">
                <button onclick="sendMessage()" id="sendBtn" disabled>发送</button>
            </div>
            <div id="sendError" class="error"></div>
        </div>

        <div class="section">
            <h2>消息记录</h2>
            <div id="messageList" class="message-list"></div>
        </div>
    </div>

    <script>
        let token = '';
        let userId = '';
        let ws = null;
        let captchaUuid = '';
        const serverUrl = 'http://localhost:8080';

        // 页面加载时刷新验证码
        window.onload = function () {
            refreshCaptcha();
        };

        // 刷新验证码
        function refreshCaptcha() {
            axios.get(`${serverUrl}/captcha`)
                .then(response => {
                    if (response.data.code === 200) {
                        document.getElementById('captchaImg').src = 'data:image/png;base64,' + response.data.data.img;
                        captchaUuid = response.data.data.uuid;
                    }
                })
                .catch(error => {
                    console.error('获取验证码失败:', error);
                    document.getElementById('loginError').textContent = '获取验证码失败';
                });
        }

        // 登录
        function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const captcha = document.getElementById('captcha').value;

            if (!username || !password || !captcha) {
                document.getElementById('loginError').textContent = '请填写完整的登录信息';
                return;
            }

            axios.post(`${serverUrl}/login`, {
                username: username,
                password: password,
                code: captcha,
                uuid: captchaUuid
            })
                .then(response => {
                    if (response.data.code === 200) {
                        token = response.data.data.token;
                        userId = response.data.data.user.userId;
                        document.getElementById('token').value = token;
                        document.getElementById('loginError').textContent = '';
                        document.getElementById('connectBtn').disabled = false;
                        appendMessage('系统', '登录成功，请点击连接按钮建立WebSocket连接', null, 'system');
                    } else {
                        document.getElementById('loginError').textContent = response.data.msg;
                        refreshCaptcha();
                    }
                })
                .catch(error => {
                    console.error('登录失败:', error);
                    document.getElementById('loginError').textContent = '登录失败: ' + (error.response?.data?.msg || error.message);
                    refreshCaptcha();
                });
        }

        // 连接WebSocket
        function connect() {
            if (!token || !userId) {
                appendMessage('系统', '请先登录', null, 'error');
                return;
            }

            if (ws) {
                appendMessage('系统', 'WebSocket已连接', null, 'error');
                return;
            }

            // 创建WebSocket连接
            const wsUrl = `ws://localhost:8080/websocket/${userId}?token=${encodeURIComponent(token)}`;
            console.log('正在连接WebSocket:', wsUrl);
            console.log('当前用户ID:', userId);
            ws = new WebSocket(wsUrl);

            // 连接成功
            ws.onopen = function () {
                console.log('WebSocket连接成功');
                document.getElementById('connectionStatus').textContent = '已连接';
                document.getElementById('connectionStatus').className = 'status online';
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                document.getElementById('sendBtn').disabled = false;
                appendMessage('系统', '连接成功', null, 'system');
            };

            // 收到消息
            ws.onmessage = function (event) {
                console.log('收到消息:', event.data);
                try {
                    const message = JSON.parse(event.data);
                    const formattedTime = message.sendTime ?
                        new Date(message.sendTime).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        }) :
                        new Date().toLocaleString('zh-CN');

                    // 处理普通消息
                    if (message.messageType === '1' || message.messageType === '2') {
                        // 如果是自己发的消息，显示在右边
                        if (message.fromUserId === parseInt(userId)) {
                            appendMessage('我', message.content, formattedTime, 'sent');
                        } else {
                            // 获取发送者用户名并显示消息
                            axios.get(`${serverUrl}/system/user/profile/get/${message.fromUserId}`)
                                .then(response => {
                                    if (response.data.code === 200) {
                                        const username = response.data.data.username;
                                        appendMessage(username, message.content, formattedTime, 'received');
                                    } else {
                                        appendMessage('用户' + message.fromUserId, message.content, formattedTime, 'received');
                                    }
                                })
                                .catch(() => {
                                    appendMessage('用户' + message.fromUserId, message.content, formattedTime, 'received');
                                });
                        }
                    } else if (message.messageType === 'system') {
                        appendMessage('系统', message.content, formattedTime, 'system');
                    } else if (message.messageType === 'error') {
                        appendMessage('错误', message.content, formattedTime, 'error');
                        if (message.content.includes('token') || message.content.includes('连接')) {
                            ws.close();
                        }
                    }
                } catch (error) {
                    console.error('解析消息失败:', error);
                    appendMessage('系统', '收到无效消息: ' + error.message, new Date().toLocaleString('zh-CN'), 'error');
                }
            };

            // 连接关闭
            ws.onclose = function (event) {
                console.log('WebSocket连接关闭:', event);
                ws = null;
                document.getElementById('connectionStatus').textContent = '未连接';
                document.getElementById('connectionStatus').className = 'status offline';
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
                document.getElementById('sendBtn').disabled = true;
                appendMessage('系统', `连接已关闭 (code: ${event.code}, reason: ${event.reason || '未知原因'})`, null, 'system');
            };

            // 连接错误
            ws.onerror = function (error) {
                console.error('WebSocket错误:', error);
                appendMessage('系统', '连接发生错误', null, 'error');
                if (ws) {
                    ws.close();
                }
            };
        }

        // 断开连接
        function disconnect() {
            if (ws) {
                ws.close();
                appendMessage('系统', '已断开连接', null, 'system');
            }
        }

        // 发送消息
        function sendMessage() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                document.getElementById('sendError').textContent = 'WebSocket未连接';
                return;
            }

            const toUserId = document.getElementById('toUserId').value;
            const content = document.getElementById('messageContent').value;

            if (!toUserId) {
                document.getElementById('sendError').textContent = '请输入接收者ID';
                return;
            }

            if (!content) {
                document.getElementById('sendError').textContent = '请输入消息内容';
                return;
            }

            // 检查是否发送给自己
            if (parseInt(toUserId) === parseInt(userId)) {
                document.getElementById('sendError').textContent = '不能发送消息给自己';
                return;
            }

            const message = {
                toUserId: parseInt(toUserId),
                content: content,
                messageType: '1'  // 1表示文本消息
            };

            try {
                ws.send(JSON.stringify(message));
                document.getElementById('messageContent').value = '';
                document.getElementById('sendError').textContent = '';
            } catch (error) {
                console.error('发送消息失败:', error);
                document.getElementById('sendError').textContent = '发送消息失败: ' + error.message;
            }
        }

        // 添加消息到列表
        function appendMessage(sender, content, time, type = 'system') {
            const messageList = document.getElementById('messageList');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;

            messageDiv.innerHTML = `
                <div class="message-header">
                    <span class="sender" style="font-weight: bold;">${sender}</span>
                    <span class="time" style="font-size: 12px; color: #999;">${time}</span>
                </div>
                <div class="message-content">${content}</div>
            `;

            // 始终添加到底部
            messageList.appendChild(messageDiv);
            // 滚动到底部
            messageList.scrollTop = messageList.scrollHeight;
        }

        // 监听回车键
        document.getElementById('messageContent').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 监听验证码输入框的回车键
        document.getElementById('captcha').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                login();
            }
        });
    </script>
</body>

</html>